package socket

import (
	"fmt"
	"net"
	"strings"
)

// Socket type
type Socket struct {
	conn       net.Conn
	RemoteAddr net.Addr
	close      chan int
}

// 创建一个 socket
func NewSocket(socketType string, addr string, callback func(msg string, conn *Socket)) {
	conn, err := net.Listen(socketType, addr)
	if err != nil {
		panic("Create A Tcp Listen Server Failed !\n")
	}
	for {
		fd, err := conn.Accept()
		if err != nil {
			panic("Accept Error !")
		}
		ch := make(chan int, 10)
		c := &Socket{conn: fd, close: ch}
		go c.Handle(callback)
	}
}

//  handle , 监听 socket 并将信息发送给回调处理
func (c *Socket) Handle(callback func(msg string, conn *Socket)) {
	var msg string
	c.RemoteAddr = c.conn.RemoteAddr()
	_ = c.Write("\r\nWelCome! \r\n" + c.RemoteAddr.String() + "\r\n")
	for {
		select {
		case <-c.close:
			close(c.close)
			return
		default:
			var buf = []byte{1}
			_, err := c.conn.Read(buf)

			if err != nil {
				fmt.Print("Read Msg Error ! \n")
				_ = c.conn.Close()
				return
			}

			if string(buf) != "\r" {
				msg = msg + string(buf)
			} else {
				msg = strings.TrimSpace(msg)
				callback(msg, c)
				msg = ""
			}
		}
	}
}

// 向客户端写入数据
func (c *Socket) Write(msg string) error {
	_, err := c.conn.Write([]byte(msg))
	return err
}

// 关闭 socket 连接
func (c *Socket) Close() error {
	err := c.conn.Close()
	c.close <- 1
	return err
}
